#include "texteditproxy.h"
#include <QDebug>
#include <QTextDocumentFragment>
#include <QRegExp>

TextEditProxy::TextEditProxy(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    m_textEdit = new QTextEdit;
    m_proxy = new QGraphicsProxyWidget(this);
    m_proxy->setWidget(m_textEdit);

    QTextCharFormat fmt;
    startEdit();
    fmt.setFontPointSize(14);
    endEdit(fmt);
}

void TextEditProxy::bold()
{
    QTextCharFormat fmt;
    startEdit();

    if (m_cur.charFormat().fontWeight() == QFont::Bold)
        fmt.setFontWeight(QFont::Normal);
    else
        fmt.setFontWeight(QFont::Bold);

    endEdit(fmt);
}

void TextEditProxy::italic()
{
    QTextCharFormat fmt;
    startEdit();
    fmt.setFontItalic(!m_cur.charFormat().fontItalic());
    endEdit(fmt);
}

void TextEditProxy::weightInc()
{
    QTextCharFormat fmt;
    startEdit();
    fmt.setFontPointSize(m_cur.charFormat().fontPointSize() + 1);
    endEdit(fmt);
}

void TextEditProxy::weightDec()
{
    QTextCharFormat fmt;
    startEdit();
    qreal ps = m_cur.charFormat().fontPointSize() - 1;
    if (ps < 7)
        ps = 7;
    fmt.setFontPointSize(ps);
    endEdit(fmt);
}

//void TextEditProxy::changeColor(const QString &newColor)
//{
//    startEdit();
//    int start = m_cur.selectionStart();
//    if (start == m_cur.position())
//        return;
//    int end = m_cur.selectionEnd();

//    qDebug() << start << end;

//    QString selected = m_textEdit->toHtml().mid(start, end - start);
//    qDebug() << selected;
//    if (selected.contains("<font")){
//        selected.replace(QRegExp("color='*'"), QString("color='%1'").arg(newColor));
//        qDebug() << selected;
//        m_cur.insertHtml(selected);
//    } else {
//        qDebug() << QString("<font color='%1'>%2</font>").arg(newColor).arg(selected);
//        m_cur.insertHtml(QString("<font color'%1'>%2</font>").arg(newColor).arg(selected));
//    }
//}

void TextEditProxy::startEdit()
{
    m_cur = m_textEdit->textCursor();

    if (!m_cur.hasSelection())
        m_cur.select(QTextCursor::WordUnderCursor);
}

void TextEditProxy::endEdit(QTextCharFormat format)
{
    m_cur.mergeCharFormat(format);
    m_textEdit->mergeCurrentCharFormat(format);
}
